<template>
  <div>
    <el-upload
      action="http://gwy-oss.oss-cn-shenzhen.aliyuncs.com"
      :data="dataObj"
      :show-file-list="false"
      :multiple="false"
      :before-upload="beforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
    >
      <img v-if="isValidImgUrl" :src="img" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <div slot="tip" style="font-size: 15px " class="el-upload__tip">
        点击图片修改<br>(只能上传jpg/png文件，且不超过10MB)
      </div>
    </el-upload>

  </div>
</template>
<script>
import {getUUID} from '../../utils/uuid'
import log from '../../views/modules/sys/log'
//使用次组件需要父组件使用v-on接受参数imgUrl 事件名uploadSuccess

export default {
  name: "singleUpload",
  props:['img'],
  computed: {
    isValidImgUrl(){
      return new RegExp("http*").test(this.img);
    }
    // {
    //   return (this.img!==''&&this.resCode===0)?this.updateForm.headPortrait:this.userInfo.headPortrait
    // }
  },
  mounted () {

  },
  data() {
    return {

      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        // callback:'',
      },
      // resCode:'0',
    };
  },
  methods: {

    beforeUpload(file) {
      let _self = this;
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl("/oss/policy"),
          method: "get"
        }).then((res) => {
            let response=res.data
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key = response.data.dir + getUUID() + "_${filename}";
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            resolve(true);
          })
          .catch((err) => {
            reject(false);
          });
      });
    },
    handleUploadSuccess(res, file) {
      console.log(this.dataObj)
      this.img=this.dataObj.host+"/"+this.dataObj.key.replace("_${filename}","_"+file.raw.name)
      this.$message({message:'上传成功!',type:'success',customClass:'zZindex'});
      console.log(this.img)
      this.$emit("uploadSuccess",this.img)
    },
    handleUploadError(res,file){
      this.$message({message:'上传失败!',type:'error',customClass:'zZindex'});

    }
  },

};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


